package com.huan.study.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author huan.fu
 * @date 2023/1/15 - 00:03
 */

public class ReportDefaultJsonSerializer extends StdSerializer<Object> {

    private static final Logger log = LoggerFactory.getLogger(ReportDefaultJsonSerializer.class);

    protected ReportDefaultJsonSerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        try {
            if (null == value) {
                writeDefaultValue(jsonGenerator);
                return;
            }

            if (intValue(value)) {
                if ((int) value == 0) {
                    writeDefaultValue(jsonGenerator);
                } else {
                    jsonGenerator.writeNumber((int) value);
                }
                return;
            }
            if (longValue(value)) {
                if ((long) value == 0) {
                    writeDefaultValue(jsonGenerator);
                } else {
                    jsonGenerator.writeNumber((long) value);
                }
                return;
            }
            if (bigDecimalValue(value)) {
                if (((BigDecimal) value).compareTo(BigDecimal.ZERO) == 0) {
                    writeDefaultValue(jsonGenerator);
                } else {
                    jsonGenerator.writeNumber((BigDecimal) value);
                }
                return;
            }
            if (stringValue(value)) {
                if (value.toString().length() == 0) {
                    writeDefaultValue(jsonGenerator);
                } else {
                    jsonGenerator.writeString((String) value);
                }
                return;
            }
        } catch (Exception e) {
            log.error("序列化字段的值:[{}]出错", value, e);
            jsonGenerator.writeString("序列化值出错");
            return;
        }

        log.warn("不支持此字段类型:[{}]序列化", value.getClass());
    }

    private boolean intValue(Object value) {
        return value.getClass() == Integer.class || value.getClass() == int.class;
    }

    private boolean longValue(Object value) {
        return value.getClass() == Long.class || value.getClass() == long.class;
    }

    private boolean bigDecimalValue(Object value) {
        return value.getClass() == BigDecimal.class;
    }

    private boolean stringValue(Object value) {
        return value.getClass() == String.class;
    }

    private void writeDefaultValue(JsonGenerator jsonGenerator) throws IOException {
        jsonGenerator.writeString("-");
    }

}
